package com.cloud.nio;


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;


public class FileChannel02 {

    public static void main(String[] args) throws Exception {
        // 输入流 写入到 1.txt
        FileInputStream fileInputStream = new FileInputStream("1.txt");
        FileChannel inChannel = fileInputStream.getChannel();

        // 输入流 2.txt 读出来
        FileOutputStream fileOutputStream = new FileOutputStream("2.txt");
        FileChannel outChannel = fileOutputStream.getChannel();

        // 创建缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(512);

        while (true) {
            // 循环读取, 这里是 index 的，当读不到就是为 -1
            // 这里有一个重要的操作，一定不要忘了
            // 清空 buffer，复位
            /*
            position = 0;
            limit = ca+pacity;
            mark = -1;
            return this;
            */
            byteBuffer.clear();
            // 先从把 1.txt 读到 fileChannel ,再从fileChannel读到缓冲区去
            int read = inChannel.read(byteBuffer);
            if (read == -1) {
                // 表示已经读完了
                break;
            }
            // 将buffer 中的数据写入到 outChannel  -- 2.txt
            byteBuffer.flip();
            outChannel.write(byteBuffer);
        }

        // 关闭相关的流
        fileInputStream.close();
        fileOutputStream.close();

    }
}
